package de.hm.edu.chartservice;

import javax.ws.rs.Consumes;
import javax.ws.rs.FormParam;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;

import org.apache.http.protocol.HTTP;

import com.sun.jersey.api.client.ClientResponse.Status;

import de.hm.edu.c2dm.C2dmRecipientsContainer;
import de.hm.edu.cep.EventEngine;
import de.hm.edu.cep.OrderEvent;
import de.hm.edu.kpi.KeyIndicator;
import de.hm.edu.oradb.IDbConnection;
import de.hm.edu.oradb.OracleDbConnectionImpl;

@Path("/kpi")
public class ChartServiceImpl implements IChartService {

	/* (non-Javadoc)
	 * @see de.hm.edu.chartservice.IChartService#getProductShareXmlKpi()
	 */
	@Override
	@GET
	@Produces( { MediaType.APPLICATION_XML})
	@Path("/get_product_share")
	public KeyIndicator getProductShareXmlKpi(){
		return ProductShare.getInstance().getProductShare();
	}
	
	/* (non-Javadoc)
	 * @see de.hm.edu.chartservice.IChartService#getSalesVolumeXmlKpi()
	 */
	@Override
	@GET
	@Produces( { MediaType.APPLICATION_XML})
	@Path("/get_sales_volume")
	public KeyIndicator getSalesVolumeXmlKpi(){
		return SalesVolume.getInstance().getKeyIndicator();
	}
	
	/* (non-Javadoc)
	 * @see de.hm.edu.chartservice.IChartService#addOrderPost(java.lang.String, int)
	 */
	@Override
	@POST
	@Produces( { MediaType.TEXT_HTML })
	@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
	@Path("/add_order")
	public String addOrderPost(@FormParam("product") String product, @FormParam("amount") int amount) throws Exception{

		//create OrderEvent object and send to it CEPListener
		OrderEvent e = new OrderEvent(product, amount, null);
		EventEngine.getEps().getEPRuntime().sendEvent(e);
		
		//store Event in db
		IDbConnection con = new OracleDbConnectionImpl();
		con.insertEvent(e);
		
		return Status.ACCEPTED.toString();
	}
	/* (non-Javadoc)
	 * @see de.hm.edu.chartservice.IChartService#receiveC2DMClientToken(java.lang.String, java.lang.String)
	 */
	@Override
	@POST
	@Produces( {MediaType.TEXT_PLAIN} )
	@Consumes( {MediaType.APPLICATION_FORM_URLENCODED})
	@Path("/clientC2DM")
	public String receiveC2DMClientToken(@FormParam("deviceId") String deviceId, @FormParam("registrationId") String registrationId){
		
		//Store Recipient in DB
		C2dmRecipientsContainer recipients = new C2dmRecipientsContainer();
		recipients.addRecipient(registrationId);
		
		return "dId: " + deviceId + " regId: "  + registrationId;
	}
}
